import 'package:eshi/app/Extension.dart';
import 'package:eshi/app/shi/data/HistoryPoint.dart';
import 'package:eshi/app/shi/data/parse/TxtPointParser.dart';

/// 简单年日期方式方式的 历史
/// 文本必须没有结构也就是都是统一没有空白的的行开始 
enum Type{
    extend,   // \w+(.+).*,
    head
}
class TxtYearDataPointParser extends TxtPointParser{
  Type type;
  TxtYearDataPointParser(super.history,this.type);
  final datas = <String,List<String>>{};
  @override
  void initData(String data) {
      data = data.replaceAll("，", ",").replaceAll("（", "(").replaceAll("）", ")").replaceAll("：", ":");
      data = "${data.split( RegExp(r"\n+") ).join(",")},";
      final bReg=RegExp(r"(\d+):");
      final times = bReg.allMatches(data).map((m){ 
         return m.group(1);
      }).toList();
      final rows = data.split(bReg);
      if(rows.length>1) rows.removeAt(0);
      rows.forEachIndexed((i,text){
          parseRow("$text,", (i>=times.length ? "":times[i]));
      });


      List<HistoryPoint> points=[];
      datas.forEach((k,v){
            points.add(HistoryPoint({})
              ..name=k
              ..data = {"":v.join("\n")}
              ..startTime = int.parse(k)
              ..endTime = int.parse(k)+1
              ..enable = true
              ..history = history
            );
      });
      history.initData(points);
  }
  parseRow(text,defTime){
    RegExp(r"[^,()]+(\([^)]+\))?[^,]*,").allMatches(text).forEach((m){
            parseItem(m.group(0)!,defTime);
    }); 
  }
  parseItem(String one,String defTime){
    var time=defTime;
    final extend = RegExp(r"\((\S+)?\s*(\d{4})?,?(\d{4})?\)").firstMatch(one);
    if(extend!=null){
      if(extend.group(2)!=null) {
        time = extend.group(2)!;
      } else{
        var tStr = extend.group(1)!;
        if(RegExp(r"^\d+$").hasMatch(tStr)) {
          time = extend.group(1)!;
        }else if(RegExp(r"^\d+").hasMatch(tStr)) {
          time = tStr.split(RegExp(r"\D")).first;
        }
      } 
    }
    if(datas[time]==null) datas[time] = <String>[];
    datas[time]!.add(one.substring(0,one.length-1));
  }
  
}